package my.edu.security.password;

import cn.hutool.crypto.digest.BCrypt;
import org.springframework.stereotype.Component;

/**
 * Implementation of PasswordEncoder that uses the BCrypt strong hashing function. Clients
 * can optionally supply a "strength" (a.k.a. log rounds in BCrypt) and a SecureRandom
 * instance. The larger the strength parameter the more work will have to be done
 * (exponentially) to hash the passwords. The default value is 10.
 *
 * @author Dave Syer
 *
 */

@Component
public class BCryptPasswordEncoder implements PasswordEncoder {

    @Override
    public String encode(String pwd) {
        // 使用BCrypt进行密码加密
        //相同密码每次生成会不一样，但是对比之后相同的密码会返回true
        return BCrypt.hashpw(pwd, BCrypt.gensalt());
    }

    @Override
    public boolean matches(String rawPassword, String encodedPassword) {
        // 检查传入的参数是否为空
        if (rawPassword == null || encodedPassword == null || encodedPassword.isEmpty()) {
            return false;
        }
        // 使用BCrypt进行密码匹配
        return BCrypt.checkpw(rawPassword, encodedPassword);
    }
}